package com.icoolkj.ms.auth.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.icoolkj.ms.api.auth.dto.CaptchaDTO;
import com.icoolkj.ms.auth.service.IAuthStrategy;
import com.icoolkj.ms.common.cache.utils.RedisUtil;
import com.icoolkj.ms.common.core.constant.CommonConstants;
import com.icoolkj.ms.common.core.constant.GlobalConstants;
import com.icoolkj.ms.common.core.response.ServerResponseEntity;
import com.icoolkj.ms.common.core.utils.PrincipalUtil;
import org.dromara.sms4j.api.SmsBlend;
import org.dromara.sms4j.api.entity.SmsResponse;
import org.dromara.sms4j.core.factory.SmsFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;

/**
 * @author icoolkj
 * @version 1.0
 * @description
 * @createDate 2025/02/23 22:20
 */
@Service("sms" + IAuthStrategy.BASE_AUTH_STRATEGY)
public class AuthStrategySmsImpl extends AbstractAuthStrategy {

    private Logger logger = LoggerFactory.getLogger(AuthStrategySmsImpl.class);

    @Override
    public boolean validateCode(CaptchaDTO captchaDTO) {
        return doValidateCode(captchaDTO.getPhoneNumber(), "手机号码", captchaDTO);
    }

    /**
     * 生成验证码
     * @param captchaKey 生成验证码KEY
     * @return 验证结果
     */
    @Override
    public ServerResponseEntity generateCaptcha(String captchaKey) {
        if (!PrincipalUtil.isMobile(captchaKey)) {
            logger.error("手机号格式不正确 => {}", captchaKey);
            return ServerResponseEntity.fail("手机号格式不正确");
        }
        String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + captchaKey;
        String code = RandomUtil.randomNumbers(4);
        RedisUtil.set(verifyKey, code, CommonConstants.CAPTCHA_EXPIRATION);
        // 验证码模板id 自行处理 (查数据库或写死均可)
        String templateId = "";
        LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
        map.put("code", code);
        SmsBlend smsBlend = SmsFactory.getSmsBlend("tm1");
        SmsResponse smsResponse = smsBlend.sendMessage(captchaKey, templateId, map);
        if (!smsResponse.isSuccess()) {
            logger.error("验证码短信发送异常 => {}", smsResponse);
            return  ServerResponseEntity.fail(smsResponse.getData().toString());
        }
        return ServerResponseEntity.success();
    }

}

